﻿using LiteLauncher.WIndow_Form;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Navigation;
using MessageBox = System.Windows.Forms.MessageBox;
namespace LiteLauncher.Pages
{
    /// <summary>
    /// MainPage.xaml 的交互逻辑
    /// </summary>
    public partial class MainPage : Page
    {
        private MinecraftVersion _selectedVersion;

        public MainPage()
        {
            InitializeComponent();
            StartupLoad();
            CheckJAVAAsync(); // 调用异步方法
            AutoDetectJavaPath();
            LoadInstalledVersions();
        }
        private async void CheckJAVAAsync()
        {
            string javaVersion = await GetJavaVersionAsync();

            if (string.IsNullOrEmpty(javaVersion))
            {
                JavaVersion.Text = "未检测到Java";
                var notification = new NotificationWindow("Java版本", "未检测到JAVA", "请跳转到下载页面进行下载安装操作", null, 3000, SystemSounds.Asterisk);
                notification.Show();

                if (MessageBox.Show("是否到下载页面下载安装JAVA？", "Java未安装", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    NavigationService.Navigate(new DownloadPage());
                }
            }
            else
            {
                var notification = new NotificationWindow("Java版本", "检测到Java", $"您的Java版本是:\n {javaVersion}", null, 3000, SystemSounds.Exclamation);
                notification.Show();
                JavaVersion.Text = $"Java版本: {javaVersion}";
            }
        }

        private Task<string> GetJavaVersionAsync()
        {
            return Task.Run(() =>
            {
                try
                {
                    Process process = new Process();
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };

                    // 设置命令参数
                    startInfo.Arguments = "/c java -version"; // 使用2>&1将错误输出重定向到标准输出

                    process.StartInfo = startInfo;
                    process.Start();

                    // 读取命令输出
                    string errorOutput = process.StandardError.ReadToEnd();

                    process.WaitForExit();

                    // 检查是否有"java version"字符串来确认Java已安装
                    if (errorOutput.Contains("version") || errorOutput.Contains("openjdk version"))
                    {
                        // 提取版本号
                        string[] lines = errorOutput.Split('\n');
                        foreach (string line in lines)
                        {
                            if (line.Contains("java version") || line.Contains("openjdk version"))
                            {
                                return line.Trim(); // 返回第一行包含版本信息的内容
                            }
                        }
                    }

                    return null; // 如果没有找到版本信息，返回null表示未安装Java
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show($"获取Java版本时出错: {ex.Message}", "出错", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }
            });
        }

        //加载信息
        private void StartupLoad()
        {
            UserName.Text = $"您好！{Environment.UserName}";

            // 设置系统版本
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
            SystemVersion.Text = $"您的系统版本是: {key.GetValue("ProductName") as string}";

            // 创建并配置定时器
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000; // 每隔1秒触发一次
            timer.Tick += (sender, e) =>
            {
                // 更新时间和日期显示
                Date.Text = DateTime.Now.ToString("yyyy年MM月dd日");
                Time.Text = DateTime.Now.ToString("HH:mm:ss");
            };
            timer.Start();

            // 设置系统类型
            SystemBit.Text = Environment.Is64BitOperatingSystem ? "64位" : "32位";
        }
        private void LoadInstalledVersions()
        {
            const string mcDir = ".minecraft";
            string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            // 1. 确保.minecraft目录存在
            string minecraftRoot = Path.Combine(appDataDir, mcDir);
            try
            {
                Directory.CreateDirectory(minecraftRoot); // 自动创建目录（如果不存在）

                // 创建必要子目录
                var requiredDirs = new[] { "versions", "libraries", "assets" };
                foreach (var dir in requiredDirs)
                {
                    string fullPath = Path.Combine(minecraftRoot, dir);
                    if (!Directory.Exists(fullPath))
                    {
                        Directory.CreateDirectory(fullPath);
                        AppendLog($"已创建缺失目录: {dir}");
                    }
                }
            }
            catch (Exception ex)
            {
                AppendLog($"无法创建游戏目录: {ex.Message}");
                return;
            }

            // 2. 加载版本信息
            string versionsDir = Path.Combine(minecraftRoot, "versions");
            GameList.Items.Clear();

            // 3. 读取版本清单（如果存在）
            var manifestPath = Path.Combine(versionsDir, "version_manifest.json");
            if (File.Exists(manifestPath))
            {
                try
                {
                    var manifest = JObject.Parse(File.ReadAllText(manifestPath));
                    foreach (var versionEntry in manifest["versions"]!)
                    {
                        var versionId = versionEntry["id"]!.ToString();
                        var versionDir = Path.Combine(versionsDir, versionId);

                        if (Directory.Exists(versionDir))
                        {
                            AddVersionToGameList(versionDir, versionId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppendLog($"版本清单解析失败: {ex.Message}");
                }
            }
            else
            {
                AppendLog("未找到版本清单，尝试加载本地版本");
            }

            // 4. 加载未在清单中的版本
            try
            {
                foreach (var dir in Directory.EnumerateDirectories(versionsDir))
                {
                    var versionId = Path.GetFileName(dir);
                    if (GameList.Items.Cast<MinecraftVersion>().All(v => v.Id != versionId))
                    {
                        AddVersionToGameList(dir, versionId);
                    }
                }
            }
            catch (DirectoryNotFoundException)
            {
                AppendLog("版本目录不存在，请检查游戏安装");
            }

            // 5. 排序并显示版本
            var sortedVersions = GameList.Items.Cast<MinecraftVersion>()
                .OrderByDescending(v => v.ReleaseTime)
                .ToList();

            GameList.Items.Clear();
            foreach (var ver in sortedVersions)
            {
                GameList.Items.Add(ver);
            }

            // 6. 添加默认选择（如果有版本）
            if (GameList.Items.Count > 0)
            {
                GameList.SelectedIndex = 0;
                AppendLog($"已加载 {GameList.Items.Count} 个游戏版本");
            }
            else
            {
                AppendLog("未找到任何有效游戏版本");
            }
        }
        private void AddVersionToGameList(string versionDir, string versionId)
        {
            try
            {
                var jsonPath = Path.Combine(versionDir, $"{versionId}.json");
                if (!File.Exists(jsonPath)) return;

                var json = JObject.Parse(File.ReadAllText(jsonPath));

                // 解析主JAR文件路径
                var jarPath = GetJarPath(versionDir, json);
                if (jarPath == null) return;

                // 解析继承关系
                var inheritsFrom = json["inheritsFrom"]?.ToString();
                if (!string.IsNullOrEmpty(inheritsFrom))
                {
                    var parentDir = Path.Combine(versionDir, "..", inheritsFrom);
                    if (!Directory.Exists(parentDir)) return;
                }

                // 解析发布时间
                var releaseTime = DateTime.Parse(json["releaseTime"]!.ToString());

                GameList.Items.Add(new MinecraftVersion
                {
                    Id = versionId,
                    JsonPath = jsonPath,
                    JarPath = jarPath,
                    NativesDir = Path.Combine(versionDir, "natives"),
                    MainClass = json["mainClass"]!.ToString(),
                    ReleaseTime = releaseTime,
                    Type = json["type"]!.ToString()
                });
            }
            catch (Exception ex)
            {
                AppendLog($"加载版本 {versionId} 失败: {ex.Message}");
            }
        }

        private string GetJarPath(string versionDir, JObject json)
        {
            var clientJar = Path.Combine(versionDir, "client.jar");
            if (File.Exists(clientJar))
                return clientJar;

            var versionId = Path.GetFileName(versionDir);
            var legacyJar = Path.Combine(versionDir, $"{versionId}.jar");
            return File.Exists(legacyJar) ? legacyJar : string.Empty;
        }
        private void AutoDetectJavaPath()
        {
            AppSettings.JavaPath = AppSettings.AutoDetectJavaPath();
        }



        private async void LaunchButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedVersion == null)
            {
                AppendLog("错误：请先选择游戏版本");
                return;
            }

            if (!File.Exists(AppSettings.JavaPath))
            {
                AppendLog($"错误：Java 路径无效 - {AppSettings.JavaPath}");
                return;
            }

            try
            {
                AppendLog($"正在启动 {_selectedVersion.Id}...");

                // 基础路径
                string minecraftDir = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    ".minecraft");

                // 获取所有库文件
                var libraryPaths = Directory.GetFiles(
                    Path.Combine(minecraftDir, "libraries"),
                    "*.jar",
                    SearchOption.AllDirectories
                );

                // 构建类路径（包含主Jar和所有库）
                var classPath = new List<string>();
                foreach (var path in libraryPaths.Concat(new[] { _selectedVersion.JarPath }))
                {
                    classPath.Add($"\"{path}\"");
                }
                // 构建启动参数
                var args = new StringBuilder();
                args.Append($"-Xms{AppSettings.MinMemory}M ");
                args.Append($"-Xmx{AppSettings.MaxMemory}M ");
                args.Append($"-Djava.library.path=\"{_selectedVersion.NativesDir}\" ");
                args.Append($"-cp \"{string.Join(";", classPath)}\" ");
                args.Append("net.minecraft.client.main.Main ");
                args.Append($"--version {_selectedVersion.Id} ");
                args.Append($"--gameDir \"{minecraftDir}\" ");
                args.Append($"--assetsDir \"{Path.Combine(minecraftDir, "assets")}\" ");
                args.Append("--username Player ");          // 离线用户名
                args.Append("--accessToken 0 ");            // 离线模式必需
                args.Append("--userType legacy ");          // 认证类型
                args.Append("--versionType release");       // 版本类型

                // 配置进程启动
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = AppSettings.JavaPath,
                        Arguments = args.ToString(),
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8,  // 支持中文输出
                        StandardErrorEncoding = Encoding.UTF8
                    },
                    EnableRaisingEvents = true
                };

                // 处理输出日志
                process.OutputDataReceived += (s, data) =>
                {
                    if (!string.IsNullOrEmpty(data.Data))
                        AppendLog($"[输出] {data.Data}");
                };

                process.ErrorDataReceived += (s, data) =>
                {
                    if (!string.IsNullOrEmpty(data.Data))
                        AppendLog($"[错误] {data.Data}");
                };

                // 启动进程
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                // 异步等待退出
                await Task.Run(() => process.WaitForExit());

                // 处理退出代码
                if (process.ExitCode == 0)
                {
                    AppendLog("游戏正常退出");
                }
                else
                {
                    AppendLog($"游戏异常退出，代码：{process.ExitCode}");
                    AppendLog("可能原因：");
                    AppendLog("1. 缺少依赖库（检查libraries目录）");
                    AppendLog("2. Java版本不兼容（需要Java 8）");
                    AppendLog("3. 显卡驱动不支持OpenGL");
                }
            }
            catch (Exception ex)
            {
                AppendLog($"启动失败：{ex.Message}");
                AppendLog($"堆栈跟踪：{ex.StackTrace}");
            }
            finally
            {

            }
        }  // 使用线程安全队列和定时刷新
        private readonly ConcurrentQueue<string> _logQueue = new ConcurrentQueue<string>();

        private void AppendLog(string message)
        {
            _logQueue.Enqueue($"[{DateTime.Now:HH:mm:ss}] {message}");
            Dispatcher.InvokeAsync(FlushLogs);
        }
        private void FlushLogs()
        {
            var sb = new StringBuilder();
            while (_logQueue.TryDequeue(out var msg))
            {
                sb.AppendLine(msg);
            }
            LogTextBox.AppendText(sb.ToString());
            // 保持最多1000行
            if (LogTextBox.LineCount > 1000)
            {
                LogTextBox.Text = LogTextBox.Text.Substring(
                    LogTextBox.GetCharacterIndexFromLineIndex(500));
            }
        }

        private void GameList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _selectedVersion = GameList.SelectedItem as MinecraftVersion;
            UpdateLaunchButtonState();
        }
        private void UpdateLaunchButtonState()
        {
            LaunchButton.IsEnabled = _selectedVersion != null;
        }
    }

    public class MinecraftVersion
    {
        public string Id { get; set; } = "";
        public string JsonPath { get; set; } = "";
        public string JarPath { get; set; } = "";
        public string NativesDir { get; set; } = "";
        public string MainClass { get; set; } = "";
        public DateTime ReleaseTime { get; set; }
        public string Type { get; set; } = "";
        // 用于ComboBox显示
        public string DisplayName => $"{Id} ({Type.ToUpper()})";
    }
}